package test;

import java.lang.ref.Cleaner;
public class ConnectionManager implements AutoCloseable {
    private static final Cleaner cleaner = Cleaner.create();
    private final DatabaseConnection connection;
    private final Cleaner.Cleanable cleanable;
    public ConnectionManager() {
        this.connection = new DatabaseConnection();
        this.cleanable = cleaner.register(this, connection::close);
    }
    public void performDatabaseOperation() {
        if (!connection.isClosed()) {
            System.out.println("执行数据库操作...");
        } else {
            System.out.println("连接已关闭，无法执行操作");
        }
    }
    @Override
    public void close() {
        cleanable.clean();
    }
    private static class DatabaseConnection {
        private boolean closed = false;
        public DatabaseConnection() {
            System.out.println("连接已打开");
        }
        public void close() {
            if (!closed) {
                System.out.println("连接已关闭");
                closed = true;
            }
        }
        public boolean isClosed() {
            return closed;
        }
    }
}
